import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * @author create on 2021/7/9
 */
public class NodeCacheExample{
    static String path = "/zkTest/nodecache";
    static String connIp = "127.0.0.1";
    static CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connIp)
            .sessionTimeoutMs(60 * 1000)
            .connectionTimeoutMs(15 * 1000)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3,Integer.MAX_VALUE))
            .build();

    public static void main(String[] args)  throws Exception {
        client.start();
        client.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.PERSISTENT)
                .forPath(path, "node Cache".getBytes());

        final NodeCache nodeCache = new NodeCache(client, path);
        nodeCache.start();
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            public void nodeChanged() throws Exception {
                ChildData currentData  = nodeCache.getCurrentData();
                String data = currentData == null ? "" : new String (currentData.getData());
                System.out.println("data Change: " + data);
            }
        });

        client.setData().forPath(path, "new Data".getBytes());
        Thread.sleep(1000);
        client.setData().forPath(path, "new Data2".getBytes());
        Thread.sleep(1000);
        client.delete().deletingChildrenIfNeeded().forPath(path);
        Thread.sleep(1000);
        nodeCache.close();
        client.close();

    }
}
